import { useEffect, useState  } from 'react'
import { ScrollArea } from '@/components/ui/scroll-area'
import { useDownloadMusicMethodStore, useDownloadProviderStore, useDownloadQualityStore, usePlayMusicMethodStore } from '@/stores/music-stores'
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
import { PlayCircle, PlusCircle, Download } from 'lucide-react'
import { toast } from 'sonner'
import QualitySelectModal from './QualitySelectModal'
import musicDefaultIcon from '@/assets/images/music-default-icon.png'

import type { ReactNode } from 'react'
import type { MusicStoreRecord } from '@/types/music'

type Props = {
  musicList: MusicStoreRecord[]
  isError: boolean
  infiniteComponent: ReactNode
}

const musicProvider: {
  [key: string]: string
} = {
  'netease': '网易云',
  'kuwo': '酷我音乐',
  'tencent': 'QQ音乐',
  'migu': '咪咕音乐',
  'kugou': '酷狗音乐',
}

const lxMusicProvider: {
  [key: string]: string
} = {
  'kuwo': 'kw',
  'tencent': 'tx',
  'netease': 'wy',
  'kugou': 'kg',
  'migu': 'mg',
}

const MusicList = ({ musicList, infiniteComponent }: Props): JSX.Element => {

  // 播放音乐
  const handlePlayMusic = usePlayMusicMethodStore(state => state.playMusicMethod)
  // 下载音乐
  const handleDownloadMusic = useDownloadMusicMethodStore(state => state.downloadMusicMethod)
  // 音乐源
  const provider = useDownloadProviderStore(state => state.downloadProvider)
  const defaultQuality = useDownloadQualityStore(state => state.downloadQuality)

  const [qualitySelectModalVisible, setQualitySelectModalVisible] = useState<boolean>(false)
  const [downloadMusic, setDownloadMusic] = useState<MusicStoreRecord | null>(null)

  useEffect(() => {
    console.info('[render Component]:%c MusicList', 'color: red;', Date.now())
  })

  const onDownload = (music: MusicStoreRecord): void => {
    const _music = { ...music }
    _music.source = lxMusicProvider[music.source]
    if (!_music.source) toast.error('暂不支持该平台')
    if (handleDownloadMusic) {
      setDownloadMusic(_music)
      setQualitySelectModalVisible(true)
    }
  }

  const onSelectQualityConfirm = (quality: string): void => {
    if (handleDownloadMusic && downloadMusic) {
      handleDownloadMusic(downloadMusic, quality, provider)
      setQualitySelectModalVisible(false)
    }
  }

  return <ScrollArea className='music-list-scroll-area pr-4'>
    <div className='music-list-header sticky top-0 z-10 bg-white shadow-sm'>
      <span className='w-12 text-center px-2'>#</span>
      <span className='flex-1 px-2'>歌曲信息</span>
      <span className='w-50 px-4'>专辑</span>
      <span className='w-30 px-4'>音乐源</span>
    </div>
    {musicList.map((item: MusicStoreRecord, index: number) => <div
      className='music-list-item'
      key={index}>
      <span className='text-xs font-bold w-12 text-center px-2'>{index + 1}</span>
      <span className='inline-flex flex-1 px-2'>
        <span className='flex-1 flex'>
          <span className='inline-flex h-12 aspect-square bg-amber-50 rounded-sm'>
            <img src={musicDefaultIcon} className='h-full w-full rounded-sm' />
          </span>
          <span className='inline-flex flex-col pl-2'>
            <span className='font-bold text-sm text-ellipsis pr-4'>{item.name}</span>
            <span className='text-xs text-accent-400 pt-2 text-ellipsis'>{item.artist?.join(' / ')}</span>
          </span>
        </span>
        <span className='w-25 flex justify-between items-center gap-2 pr-4'>
          <Tooltip>
            <TooltipTrigger>
              <PlayCircle
                size={20}
                className='operation-icon'
                onClick={() => handlePlayMusic(item.id, item.source, item.quality || defaultQuality)}
              />
            </TooltipTrigger>
            <TooltipContent>播放</TooltipContent>
          </Tooltip>
          <Tooltip>
            <TooltipTrigger>
              <PlusCircle size={20} className='operation-icon' />
            </TooltipTrigger>
            <TooltipContent>添加到播放列表</TooltipContent>
          </Tooltip>
          <Tooltip>
            <TooltipTrigger>
              <Download
                size={20}
                className='operation-icon'
                onClick={() => onDownload(item)}
              />
            </TooltipTrigger>
            <TooltipContent>下载</TooltipContent>
          </Tooltip>
        </span>
      </span>
      <span className='w-50 text-sm px-4 text-ellipsis-2'>{item.album}</span>
      <span className='w-30 text-sm px-4'>{musicProvider[item.source] || '未知源'}</span>
    </div>)}
    {infiniteComponent}
    <QualitySelectModal
      className='w-60'
      title='请选择下载品质'
      visible={qualitySelectModalVisible}
      defaultQuality={defaultQuality}
      onCancel={() => setQualitySelectModalVisible(false)}
      onClose={() => setQualitySelectModalVisible(false)}
      onConfirm={onSelectQualityConfirm}>
    </QualitySelectModal>
  </ScrollArea>
}

export default MusicList
